<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>CameraBridge 测试页面</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 14px;
        }
        
        .content {
            padding: 20px;
        }
        
        .test-section {
            margin-bottom: 30px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
        }
        
        .section-header {
            background: #f5f5f5;
            padding: 15px;
            font-weight: 600;
            color: #333;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .section-content {
            padding: 20px;
        }
        
        .button-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .test-button {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .test-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .test-button:active {
            transform: translateY(0);
        }
        
        .test-button.secondary {
            background: linear-gradient(135deg, #36d1dc, #5b86e5);
        }
        
        .test-button.warning {
            background: linear-gradient(135deg, #f093fb, #f5576c);
        }
        
        .test-button.danger {
            background: linear-gradient(135deg, #ff6b6b, #ee5a24);
        }
        
        .test-button.success {
            background: linear-gradient(135deg, #4ecdc4, #44a08d);
        }
        
        .test-button.info {
            background: linear-gradient(135deg, #17a2b8, #138496);
        }
        
        .test-button.info:hover {
            background: linear-gradient(135deg, #138496, #117a8b);
        }
        
        .test-button.warning {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            color: #212529;
        }
        
        .test-button.warning:hover {
            background: linear-gradient(135deg, #e0a800, #d39e00);
        }
        
        .test-button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .test-button.loading {
            pointer-events: none;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 8px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .log-area {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.4;
        }
        
        .log-entry {
            margin-bottom: 5px;
            padding: 3px 0;
        }
        
        .log-entry.info {
            color: #007bff;
        }
        
        .log-entry.success {
            color: #28a745;
            font-weight: 500;
        }
        
        .log-entry.warning {
            color: #ffc107;
            font-weight: 500;
        }
        
        .log-entry.error {
            color: #dc3545;
            font-weight: 500;
        }
        
        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-ready {
            background: #28a745;
        }
        
        .status-not-ready {
            background: #dc3545;
        }
        
        .status-unknown {
            background: #ffc107;
        }
        
        .camera-status {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .camera-status h3 {
            color: #1976d2;
            margin-bottom: 10px;
        }
        
        .status-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }
        
        .clear-log {
            background: #6c757d;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            font-size: 12px;
            cursor: pointer;
            margin-bottom: 10px;
        }
        
        .clear-log:hover {
            background: #5a6268;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📷 CameraBridge 测试</h1>
            <p>测试 HarmonyOS 原生相机 C++ 接口</p>
        </div>
        
        <div class="content">
            <!-- 相机状态 -->
            <div class="camera-status">
                <h3>相机状态</h3>
                <div class="status-item">
                    <span class="status-indicator status-unknown" id="camera-status-indicator"></span>
                    <span id="camera-status-text">未知</span>
                </div>
                <div class="status-item">
                    <span>Surface ID: </span>
                    <span id="surface-id">-</span>
                </div>
                <div class="status-item">
                    <span>Photo Surface ID: </span>
                    <span id="photo-surface-id">-</span>
                </div>
            
            <!-- 基础相机操作 -->
            <div class="test-section">
                <div class="section-header">基础相机操作</div>
                <div class="section-content">
                    <div class="button-grid">
                        <button class="test-button success" onclick="openSystemCamera()">📱 打开相机</button>
                        <button class="test-button" onclick="initializeCamera()">初始化相机</button>
                        <button class="test-button info" onclick="checkCameraStatus()">📊 检查状态</button>
                        <button class="test-button warning" onclick="testBackendStatus()">测试后端状态</button>
                        <button class="test-button secondary" onclick="takePhoto()">拍照</button>
                        <button class="test-button secondary" onclick="takePhotoSimple()">简单拍照</button>
                        <button class="test-button warning" onclick="switchCamera()">切换摄像头</button>
                        <button class="test-button danger" onclick="releaseCamera()">释放相机</button>
                    </div>
                </div>
            </div>
            </div>
            
            <!-- 高级相机功能 -->
            <div class="test-section">
                <div class="section-header">高级相机功能</div>
                <div class="section-content">
                    <div class="button-grid">
                        <button class="test-button" onclick="testZoom()">变焦测试</button>
                        <button class="test-button secondary" onclick="testFlash()">闪光灯测试</button>
                        <button class="test-button warning" onclick="testFocus()">对焦测试</button>
                        <button class="test-button success" onclick="getVideoFrameInfo()">视频帧信息</button>
                    </div>
                </div>
            </div>
            
            <!-- 视频录制 -->
            <div class="test-section">
                <div class="section-header">视频录制</div>
                <div class="section-content">
                    <div class="button-grid">
                        <button class="test-button" onclick="startVideoRecording()">开始录制</button>
                        <button class="test-button danger" onclick="stopVideoRecording()">停止录制</button>
                        <button class="test-button secondary" onclick="testVideoStabilization()">防抖测试</button>
                    </div>
                </div>
            </div>
            
            <!-- 日志区域 -->
            <div class="test-section">
                <div class="section-header">测试日志</div>
                <div class="section-content">
                    <button class="clear-log" onclick="clearLog()">清空日志</button>
                    <div class="log-area" id="log-area"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let cameraInstance = null;
        let currentCameraIndex = 0; // 0: 后置, 1: 前置
        let isRecording = false;
        
        // 全局变量用于保存Surface ID
        window.lastSurfaceId = null;
        window.lastPhotoSurfaceId = null;
        
        // 日志函数
        function log(message, type = 'info') {
            const logArea = document.getElementById('log-area');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry ${type}`;
            logEntry.textContent = `[${timestamp}] ${message}`;
            logArea.appendChild(logEntry);
            logArea.scrollTop = logArea.scrollHeight;
            
            // 同时输出到控制台，以便 OnConsoleEvent 能够捕获
            switch (type) {
                case 'error':
                    console.error(`[CameraBridge] ${message}`);
                    break;
                case 'warning':
                    console.warn(`[CameraBridge] ${message}`);
                    break;
                case 'success':
                    console.info(`[CameraBridge] ${message}`);
                    break;
                case 'info':
                default:
                    console.log(`[CameraBridge] ${message}`);
                    break;
            }
        }
        
        function clearLog() {
            document.getElementById('log-area').innerHTML = '';
        }
        
        // 手动检查相机状态
        async function checkCameraStatus() {
            log('🔍 开始全面检查相机状态...', 'info');
            
            try {
                // === 第一步：环境检查 ===
                log('📋 步骤1: 检查运行环境', 'info');
                
                if (typeof window.CameraBridge === 'undefined') {
                    log('❌ CameraBridge 不可用 - 请确保在HarmonyOS环境中运行', 'error');
                    await updateCameraStatus();
                    return false;
                }
                log('✅ CameraBridge 可用', 'success');
                
                if (!cameraInstance) {
                    log('⚠️ 相机实例未创建 - 请先点击"初始化相机"按钮', 'warning');
                    await updateCameraStatus();
                    return false;
                }
                log('✅ 相机实例已创建', 'success');
                
                // === 第二步：方法可用性检查 ===
                log('📋 步骤2: 检查相机方法可用性', 'info');
                
                const requiredMethods = [
                    { name: 'isReady', required: true },
                    { name: 'getCurrentSurfaceId', required: true },
                    { name: 'getCurrentPhotoSurfaceId', required: false },
                    { name: 'getCameraStatus', required: false },
                    { name: 'initializeCamera', required: true },
                    { name: 'takePhoto', required: true },
                    { name: 'releaseCamera', required: true }
                ];
                
                let methodsOk = true;
                requiredMethods.forEach(({ name, required }) => {
                    const available = typeof cameraInstance[name] === 'function';
                    const status = available ? '✅' : (required ? '❌' : '⚠️');
                    const level = available ? 'success' : (required ? 'error' : 'warning');
                    log(`${status} ${name}: ${available ? '可用' : '不可用'}${required ? ' (必需)' : ' (可选)'}`, level);
                    
                    if (required && !available) {
                        methodsOk = false;
                    }
                });
                
                if (!methodsOk) {
                    log('❌ 关键方法缺失，相机功能可能不完整', 'error');
                    return false;
                }
                
                // === 第三步：后端状态检查 ===
                log('📋 步骤3: 检查后端状态', 'info');
                
                let backendStatus = null;
                let backendStatusOk = false;
                
                if (typeof cameraInstance.getCameraStatus === 'function') {
                    try {
                        log('🔄 正在从后端获取状态...', 'info');
                        backendStatus = await cameraInstance.getCameraStatus();
                        
                        if (backendStatus && backendStatus.success) {
                            backendStatusOk = true;
                            log('✅ 后端状态获取成功', 'success');
                            log(`📊 后端详细状态:`, 'info');
                            log(`   - 相机就绪: ${backendStatus.isReady ? '✅ 是' : '❌ 否'}`, backendStatus.isReady ? 'success' : 'warning');
                            log(`   - Surface ID: ${backendStatus.surfaceId || '未设置'}`, backendStatus.surfaceId ? 'success' : 'warning');
                            log(`   - Photo Surface ID: ${backendStatus.photoSurfaceId || '未设置'}`, backendStatus.photoSurfaceId ? 'success' : 'warning');
                            log(`   - 消息: ${backendStatus.message || '无'}`, 'info');
                        } else {
                            log('⚠️ 后端状态获取失败或返回错误', 'warning');
                            if (backendStatus && backendStatus.message) {
                                log(`   错误信息: ${backendStatus.message}`, 'warning');
                            }
                            log(`💡 可能原因: 相机未正确初始化或后端服务异常`, 'info');
                        }
                    } catch (e) {
                        log(`❌ 后端状态获取异常: ${e.message}`, 'error');
                        log(`💡 可能原因: 相机未正确初始化或后端服务异常`, 'info');
                    }
                } else {
                    log('⚠️ getCameraStatus方法不可用，跳过后端状态检查', 'warning');
                }
                
                // === 第四步：前端状态检查 ===
                log('📋 步骤4: 检查前端状态', 'info');
                
                let frontendReady = false;
                if (typeof cameraInstance.isReady === 'function') {
                    try {
                        frontendReady = cameraInstance.isReady();
                        log(`📱 前端相机就绪: ${frontendReady ? '✅ 是' : '❌ 否'}`, frontendReady ? 'success' : 'warning');
                    } catch (e) {
                        log(`❌ 前端就绪状态检查失败: ${e.message}`, 'error');
                    }
                } else {
                    log('❌ isReady方法不可用', 'error');
                }
                
                // === 第五步：Surface ID 多源检查 ===
                log('📋 步骤5: 检查Surface ID (多源对比)', 'info');
                
                const surfaceIdSources = {
                    method: null,
                    property: null,
                    global: null,
                    backend: null
                };
                
                const photoSurfaceIdSources = {
                    method: null,
                    property: null,
                    global: null,
                    backend: null
                };
                
                // 方法获取
                if (typeof cameraInstance.getCurrentSurfaceId === 'function') {
                    try {
                        surfaceIdSources.method = cameraInstance.getCurrentSurfaceId();
                    } catch (e) {
                        log(`⚠️ getCurrentSurfaceId方法调用失败: ${e.message}`, 'warning');
                    }
                }
                
                if (typeof cameraInstance.getCurrentPhotoSurfaceId === 'function') {
                    try {
                        photoSurfaceIdSources.method = cameraInstance.getCurrentPhotoSurfaceId();
                    } catch (e) {
                        log(`⚠️ getCurrentPhotoSurfaceId方法调用失败: ${e.message}`, 'warning');
                    }
                }
                
                // 属性获取
                surfaceIdSources.property = cameraInstance.surfaceId || null;
                photoSurfaceIdSources.property = cameraInstance.photoSurfaceId || null;
                
                // 全局变量获取
                surfaceIdSources.global = window.lastSurfaceId || null;
                photoSurfaceIdSources.global = window.lastPhotoSurfaceId || null;
                
                // 后端获取
                if (backendStatus && backendStatus.success) {
                    surfaceIdSources.backend = backendStatus.surfaceId || null;
                    photoSurfaceIdSources.backend = backendStatus.photoSurfaceId || null;
                }
                
                // 报告Surface ID状态
                log('📍 Surface ID 多源对比:', 'info');
                Object.entries(surfaceIdSources).forEach(([source, value]) => {
                    const status = value ? '✅' : '❌';
                    log(`   ${source}: ${status} ${value || '未设置'}`, value ? 'success' : 'warning');
                });
                
                log('📍 Photo Surface ID 多源对比:', 'info');
                Object.entries(photoSurfaceIdSources).forEach(([source, value]) => {
                    const status = value ? '✅' : '❌';
                    log(`   ${source}: ${status} ${value || '未设置'}`, value ? 'success' : 'warning');
                });
                
                // === 第六步：一致性检查 ===
                log('📋 步骤6: 数据一致性检查', 'info');
                
                const surfaceIdValues = Object.values(surfaceIdSources).filter(v => v);
                const photoSurfaceIdValues = Object.values(photoSurfaceIdSources).filter(v => v);
                
                const surfaceIdConsistent = surfaceIdValues.length <= 1 || surfaceIdValues.every(v => v === surfaceIdValues[0]);
                const photoSurfaceIdConsistent = photoSurfaceIdValues.length <= 1 || photoSurfaceIdValues.every(v => v === photoSurfaceIdValues[0]);
                
                log(`🔄 Surface ID 一致性: ${surfaceIdConsistent ? '✅ 一致' : '⚠️ 不一致'}`, surfaceIdConsistent ? 'success' : 'warning');
                log(`🔄 Photo Surface ID 一致性: ${photoSurfaceIdConsistent ? '✅ 一致' : '⚠️ 不一致'}`, photoSurfaceIdConsistent ? 'success' : 'warning');
                
                if (!surfaceIdConsistent) {
                    log('⚠️ Surface ID 在不同源之间不一致，可能存在同步问题', 'warning');
                }
                
                if (!photoSurfaceIdConsistent) {
                    log('⚠️ Photo Surface ID 在不同源之间不一致，可能存在同步问题', 'warning');
                }
                
                // === 第七步：更新UI状态 ===
                log('📋 步骤7: 更新UI状态显示', 'info');
                await updateCameraStatus();
                
                // === 总结报告 ===
                log('📊 === 状态检查总结 ===', 'info');
                log(`🏗️ 环境: ${typeof window.CameraBridge !== 'undefined' ? '✅ 正常' : '❌ 异常'}`, 'info');
                log(`📱 实例: ${cameraInstance ? '✅ 已创建' : '❌ 未创建'}`, 'info');
                log(`🔧 方法: ${methodsOk ? '✅ 完整' : '❌ 缺失'}`, 'info');
                log(`🎯 前端就绪: ${frontendReady ? '✅ 是' : '❌ 否'}`, 'info');
                log(`🌐 后端状态: ${backendStatusOk ? '✅ 正常' : '⚠️ 异常'}`, 'info');
                log(`📍 Surface ID: ${surfaceIdValues.length > 0 ? '✅ 已设置' : '❌ 未设置'}`, 'info');
                log(`📸 Photo Surface ID: ${photoSurfaceIdValues.length > 0 ? '✅ 已设置' : '❌ 未设置'}`, 'info');
                
                // 整体状态评估
                const overallOk = (typeof window.CameraBridge !== 'undefined') && 
                                 cameraInstance && 
                                 methodsOk && 
                                 frontendReady && 
                                 backendStatusOk && 
                                 surfaceIdValues.length > 0;
                                 
                log(`🎯 整体状态: ${overallOk ? '✅ 正常' : '❌ 异常'}`, overallOk ? 'success' : 'error');
                
                return overallOk;
                
            } catch (error) {
                log(`❌ 状态检查过程中发生异常: ${error.message}`, 'error');
                console.error('checkCameraStatus error:', error);
                return false;
            }
        }
        
        // 更新相机状态显示
        async function updateCameraStatus() {
            const indicator = document.getElementById('camera-status-indicator');
            const text = document.getElementById('camera-status-text');
            const surfaceId = document.getElementById('surface-id');
            const photoSurfaceId = document.getElementById('photo-surface-id');
            
            try {
                // 调试信息
                log(`🔍 检查相机实例: ${cameraInstance ? '存在' : '不存在'}`, 'info');
                
                if (cameraInstance) {
                    // 优先使用getCameraStatus方法获取后端真实状态
                    if (typeof cameraInstance.getCameraStatus === 'function') {
                        try {
                            log(`🔄 正在从后端获取相机状态...`, 'info');
                            const status = await cameraInstance.getCameraStatus();
                            log(`📊 后端状态: ${JSON.stringify(status)}`, 'info');
                            
                            if (status && status.success) {
                                const isReady = status.isReady;
                                const currentSurfaceId = status.surfaceId || '';
                                const currentPhotoSurfaceId = status.photoSurfaceId || '';
                                
                                log(`🎯 后端相机就绪状态: ${isReady}`, isReady ? 'success' : 'warning');
                                log(`📍 后端Surface ID: ${currentSurfaceId}`, 'info');
                                log(`📍 后端Photo Surface ID: ${currentPhotoSurfaceId}`, 'info');
                                
                                if (isReady) {
                                    indicator.className = 'status-indicator status-ready';
                                    text.textContent = '已就绪';
                                } else {
                                    indicator.className = 'status-indicator status-not-ready';
                                    text.textContent = '未初始化';
                                }
                                
                                surfaceId.textContent = currentSurfaceId || '-';
                                photoSurfaceId.textContent = currentPhotoSurfaceId || '-';
                                
                                log(`✅ 状态更新完成(后端): Surface ID=${currentSurfaceId || '无'}, Photo Surface ID=${currentPhotoSurfaceId || '无'}`, 'success');
                                return; // 成功获取后端状态，直接返回
                            } else {
                                log(`⚠️ 后端状态获取失败，使用前端状态`, 'warning');
                            }
                        } catch (e) {
                            log(`❌ 获取后端状态失败: ${e.message}，使用前端状态`, 'error');
                        }
                    }
                    
                    // 备用方案：使用前端本地状态
                    log(`🔄 使用前端本地状态...`, 'info');
                    const hasIsReady = typeof cameraInstance.isReady === 'function';
                    const hasGetCurrentSurfaceId = typeof cameraInstance.getCurrentSurfaceId === 'function';
                    const hasGetCurrentPhotoSurfaceId = typeof cameraInstance.getCurrentPhotoSurfaceId === 'function';
                    
                    log(`📋 方法检查: isReady=${hasIsReady}, getCurrentSurfaceId=${hasGetCurrentSurfaceId}, getCurrentPhotoSurfaceId=${hasGetCurrentPhotoSurfaceId}`, 'info');
                    
                    // 检查相机是否就绪
                    const isReady = hasIsReady ? cameraInstance.isReady() : false;
                    log(`🎯 前端相机就绪状态: ${isReady}`, isReady ? 'success' : 'warning');
                    
                    if (isReady) {
                        indicator.className = 'status-indicator status-ready';
                        text.textContent = '已就绪';
                        
                        // 尝试多种方式获取Surface ID
                        let currentSurfaceId = '';
                        let currentPhotoSurfaceId = '';
                        
                        // 方法1: 通过函数获取
                        if (hasGetCurrentSurfaceId) {
                            try {
                                currentSurfaceId = cameraInstance.getCurrentSurfaceId() || '';
                                log(`📍 通过函数获取Surface ID: ${currentSurfaceId}`, 'info');
                            } catch (e) {
                                log(`❌ 函数获取Surface ID失败: ${e.message}`, 'error');
                            }
                        }
                        
                        if (hasGetCurrentPhotoSurfaceId) {
                            try {
                                currentPhotoSurfaceId = cameraInstance.getCurrentPhotoSurfaceId() || '';
                                log(`📍 通过函数获取Photo Surface ID: ${currentPhotoSurfaceId}`, 'info');
                            } catch (e) {
                                log(`❌ 函数获取Photo Surface ID失败: ${e.message}`, 'error');
                            }
                        }
                        
                        // 方法2: 通过属性获取（备用方案）
                        if (!currentSurfaceId && cameraInstance.surfaceId) {
                            currentSurfaceId = cameraInstance.surfaceId;
                            log(`📍 通过属性获取Surface ID: ${currentSurfaceId}`, 'info');
                        }
                        
                        if (!currentPhotoSurfaceId && cameraInstance.photoSurfaceId) {
                            currentPhotoSurfaceId = cameraInstance.photoSurfaceId;
                            log(`📍 通过属性获取Photo Surface ID: ${currentPhotoSurfaceId}`, 'info');
                        }
                        
                        // 方法3: 使用全局变量（如果有的话）
                        if (!currentSurfaceId && window.lastSurfaceId) {
                            currentSurfaceId = window.lastSurfaceId;
                            log(`📍 使用全局Surface ID: ${currentSurfaceId}`, 'info');
                        }
                        
                        if (!currentPhotoSurfaceId && window.lastPhotoSurfaceId) {
                            currentPhotoSurfaceId = window.lastPhotoSurfaceId;
                            log(`📍 使用全局Photo Surface ID: ${currentPhotoSurfaceId}`, 'info');
                        }
                        
                        surfaceId.textContent = currentSurfaceId || '-';
                        photoSurfaceId.textContent = currentPhotoSurfaceId || '-';
                        
                        log(`✅ 状态更新完成(前端): Surface ID=${currentSurfaceId || '无'}, Photo Surface ID=${currentPhotoSurfaceId || '无'}`, 'success');
                    } else {
                        indicator.className = 'status-indicator status-not-ready';
                        text.textContent = '未初始化';
                        surfaceId.textContent = '-';
                        photoSurfaceId.textContent = '-';
                        log(`⚠️ 相机未就绪`, 'warning');
                    }
                } else {
                    indicator.className = 'status-indicator status-not-ready';
                    text.textContent = '未创建';
                    surfaceId.textContent = '-';
                    photoSurfaceId.textContent = '-';
                    log(`❌ 相机实例未创建`, 'error');
                }
            } catch (error) {
                indicator.className = 'status-indicator status-not-ready';
                text.textContent = '状态错误';
                surfaceId.textContent = '-';
                photoSurfaceId.textContent = '-';
                log(`❌ 相机状态检查错误: ${error.message}`, 'error');
                console.error('updateCameraStatus error:', error);
            }
        }
        
        // 显示加载状态
        function showLoading(button) {
            const originalText = button.textContent;
            button.classList.add('loading');
            button.innerHTML = '<div class="loading-spinner"></div>' + originalText;
            button.disabled = true;
            
            return () => {
                button.classList.remove('loading');
                button.textContent = originalText;
                button.disabled = false;
            };
        }
        
        // 测试后端状态（专门用于调试）
        async function testBackendStatus() {
            try {
                log('🧪 开始测试后端状态获取...', 'info');
                
                // 检查 CameraBridge 是否可用
                if (!window.CameraBridge) {
                    log('❌ CameraBridge 不可用', 'error');
                    return;
                }
                
                // 检查相机实例
                if (!cameraInstance) {
                    log('❌ 相机实例未创建，尝试创建...', 'warning');
                    cameraInstance = new window.CameraBridge();
                    log('✅ 相机实例已创建', 'success');
                }
                
                // 检查getCameraStatus方法
                if (typeof cameraInstance.getCameraStatus !== 'function') {
                    log('❌ getCameraStatus方法不存在', 'error');
                    return;
                }
                
                log('🔄 正在调用后端getCameraStatus...', 'info');
                
                // 直接调用getCameraStatus
                const status = await cameraInstance.getCameraStatus();
                
                log('📊 后端返回的完整状态:', 'info');
                log(JSON.stringify(status, null, 2), 'info');
                
                if (status) {
                    log(`✅ 成功获取状态: success=${status.success}`, 'success');
                    log(`📋 消息: ${status.message || '无'}`, 'info');
                    log(`🎯 相机就绪: ${status.isReady}`, status.isReady ? 'success' : 'warning');
                    log(`📍 Surface ID: ${status.surfaceId || '无'}`, status.surfaceId ? 'success' : 'warning');
                    log(`📍 Photo Surface ID: ${status.photoSurfaceId || '无'}`, status.photoSurfaceId ? 'success' : 'warning');
                    
                    // 手动更新UI
                    const indicator = document.getElementById('camera-status-indicator');
                    const text = document.getElementById('camera-status-text');
                    const surfaceIdElement = document.getElementById('surface-id');
                    const photoSurfaceIdElement = document.getElementById('photo-surface-id');
                    
                    if (status.success && status.isReady) {
                        indicator.className = 'status-indicator status-ready';
                        text.textContent = '已就绪';
                        surfaceIdElement.textContent = status.surfaceId || '-';
                        photoSurfaceIdElement.textContent = status.photoSurfaceId || '-';
                        log('✅ UI已手动更新', 'success');
                    } else {
                        indicator.className = 'status-indicator status-not-ready';
                        text.textContent = '未初始化';
                        surfaceIdElement.textContent = '-';
                        photoSurfaceIdElement.textContent = '-';
                        log('⚠️ 相机未就绪，UI已更新', 'warning');
                    }
                } else {
                    log('❌ 后端返回空状态', 'error');
                }
                
            } catch (error) {
                log(`❌ 测试后端状态失败: ${error.message}`, 'error');
                log(`错误详情: ${error.stack || error}`, 'error');
            }
        }
        
        // 打开系统相机
        async function openSystemCamera() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                log('📱 正在打开系统相机...', 'info');
                
                // 检查 CameraBridge 是否可用
                if (!window.CameraBridge) {
                    throw new Error('CameraBridge 不可用，请确保在 HarmonyOS 环境中运行');
                }
                
                // 创建相机实例（如果还没有）
                if (!cameraInstance) {
                    cameraInstance = new window.CameraBridge();
                    log('✅ CameraBridge 实例创建成功', 'success');
                }
                
                // 调用打开系统相机功能
                const result = await cameraInstance.openSystemCamera({
                    quality: 95,
                    cameraDeviceIndex: currentCameraIndex
                });
                
                log(`📱 系统相机返回结果: ${JSON.stringify(result)}`, 'info');
                
                if (result && result.success) {
                    if (result.filePath) {
                        log(`✅ 系统相机拍照成功！照片已保存: ${result.filePath}`, 'success');
                        log(`📷 照片URI: ${result.filePath}`, 'info');
                        
                        // 显示拍照成功的额外信息
                        log(`🎯 使用摄像头: ${currentCameraIndex === 0 ? '后置' : '前置'}`, 'info');
                        
                    } else if (result.cancelled) {
                        log('ℹ️ 用户取消了拍照操作', 'warning');
                    } else {
                        log('✅ 系统相机调用成功（无照片返回）', 'success');
                    }
                } else if (result && result.cancelled) {
                    log('ℹ️ 用户取消了拍照操作', 'warning');
                } else {
                    log('❌ 系统相机调用失败，未知错误', 'error');
                }
                
                updateCameraStatus();
                
            } catch (error) {
                log(`❌ 打开系统相机失败: ${error.message}`, 'error');
                console.error('Open system camera error:', error);
                
                // 提供详细的错误信息和解决方案
                if (error.message.includes('无法获取应用上下文')) {
                    log('💡 提示: 应用上下文获取失败，请确保在正确的HarmonyOS环境中运行', 'info');
                } else if (error.message.includes('cancel') || error.message.includes('取消')) {
                    log('ℹ️ 用户取消了系统相机操作', 'warning');
                } else if (error.message.includes('permission')) {
                    log('💡 提示: 可能缺少相机权限，请检查应用权限设置', 'info');
                } else {
                    log('💡 提示: 如果系统相机不可用，您可以使用"初始化相机"功能', 'info');
                }
            } finally {
                hideLoading();
            }
        }
        
        // 基础相机操作
        async function initializeCamera() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                log('开始初始化相机...', 'info');
                
                // 检查 CameraBridge 是否可用
                if (!window.CameraBridge) {
                    throw new Error('CameraBridge 不可用，请确保在 HarmonyOS 环境中运行');
                }
                
                // 创建相机实例
                cameraInstance = new window.CameraBridge();
                log('✅ CameraBridge 实例创建成功', 'success');
                
                // 生成 Surface ID
                const surfaceId = `preview_surface_${Date.now()}`;
                
                // 保存到全局变量和实例属性
                window.lastSurfaceId = surfaceId;
                if (cameraInstance) {
                    cameraInstance.surfaceId = surfaceId;
                }
                
                log(`🆔 生成Surface ID: ${surfaceId}`, 'info');
                
                // 初始化相机 - 使用新的接口
                const result = await cameraInstance.initializeCamera(surfaceId, {
                    cameraDeviceIndex: currentCameraIndex,
                    focusMode: 1, // 自动对焦
                    quality: 95
                });
                
                log(`📷 相机初始化结果: ${JSON.stringify(result)}`, 'info');
                
                if (result) {
                    // 标记为已初始化
                    cameraInstance._isInitialized = true;
                    
                    // 确保surfaceId被正确保存到前端实例
                    if (result.surfaceId) {
                        cameraInstance.surfaceId = result.surfaceId;
                        window.lastSurfaceId = result.surfaceId;
                        log(`✅ Surface ID已保存到前端实例: ${result.surfaceId}`, 'success');
                    } else {
                        // 如果返回结果中没有surfaceId，使用我们生成的
                        cameraInstance.surfaceId = surfaceId;
                        window.lastSurfaceId = surfaceId;
                        log(`✅ 使用生成的Surface ID: ${surfaceId}`, 'success');
                    }
                    
                    // 确保photoSurfaceId被正确保存到前端实例
                    if (result.photoSurfaceId) {
                        cameraInstance.photoSurfaceId = result.photoSurfaceId;
                        window.lastPhotoSurfaceId = result.photoSurfaceId;
                        log(`✅ Photo Surface ID已保存到前端实例: ${result.photoSurfaceId}`, 'success');
                    } else {
                        // 如果返回结果中没有photoSurfaceId，生成一个
                        const photoSurfaceId = `photo_surface_${Date.now()}`;
                        cameraInstance.photoSurfaceId = photoSurfaceId;
                        window.lastPhotoSurfaceId = photoSurfaceId;
                        log(`✅ 生成Photo Surface ID: ${photoSurfaceId}`, 'success');
                    }
                    
                    log(`✅ 相机初始化成功 - Surface ID: ${cameraInstance.surfaceId}`, 'success');
                    log(`✅ 相机初始化成功 - Photo Surface ID: ${cameraInstance.photoSurfaceId}`, 'success');
                    log(`当前摄像头: ${currentCameraIndex === 0 ? '后置' : '前置'}`, 'info');
                    
                    // 立即更新状态
                    updateCameraStatus();
                    
                    // 等待一小段时间再次更新确保状态同步
                    setTimeout(async () => {
                        await updateCameraStatus();
                        log('📊 相机状态已更新', 'info');
                    }, 100);
                } else {
                    throw new Error('相机初始化返回失败结果');
                }
                
                updateCameraStatus();
                
            } catch (error) {
                log(`❌ 相机初始化失败: ${error.message}`, 'error');
                console.error('Camera initialization error:', error);
                cameraInstance = null;
                updateCameraStatus();
            } finally {
                hideLoading();
            }
        }
        
        async function takePhoto() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                log('开始拍照...', 'info');
                
                // 生成Photo Surface ID
                const photoSurfaceId = `photo_surface_${Date.now()}`;
                
                log(`🆔 生成Photo Surface ID: ${photoSurfaceId}`, 'info');
                
                const result = await cameraInstance.takePhoto({
                    quality: 95,
                    allowEdit: false,
                    resultType: 'file',
                    cameraDeviceIndex: currentCameraIndex
                });
                
                if (result) {
                    // 拍照成功后保存photoSurfaceId到前端实例
                    cameraInstance.photoSurfaceId = photoSurfaceId;
                    window.lastPhotoSurfaceId = photoSurfaceId;
                    log(`✅ Photo Surface ID已保存到前端实例: ${photoSurfaceId}`, 'success');
                    
                    log('✅ 拍照成功，结果: ' + JSON.stringify(result), 'success');
                } else {
                    log('❌ 拍照失败', 'error');
                }
                
                // 更新状态显示
                updateCameraStatus();
                
            } catch (error) {
                log(`❌ 拍照异常: ${error.message}`, 'error');
                console.error('Take photo error:', error);
            } finally {
                hideLoading();
            }
        }
        
        async function takePhotoSimple() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                log('开始简单拍照...', 'info');
                
                const photoPath = await cameraInstance.takePictureSimple();
                log(`简单拍照成功! 照片路径: ${photoPath}`, 'success');
                
            } catch (error) {
                log(`简单拍照失败: ${error.message}`, 'error');
            } finally {
                hideLoading();
            }
        }
        
        async function switchCamera() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                log('切换摄像头...', 'info');
                
                // 释放当前相机
                await cameraInstance.releaseCamera();
                log('当前相机已释放', 'info');
                
                // 切换摄像头索引
                currentCameraIndex = currentCameraIndex === 0 ? 1 : 0;
                log(`切换到${currentCameraIndex === 0 ? '后置' : '前置'}摄像头`, 'info');
                
                // 重新初始化
                const surfaceId = `preview_surface_${Date.now()}`;
                await cameraInstance.initializeCamera(surfaceId, {
                    cameraDeviceIndex: currentCameraIndex,
                    focusMode: 1,
                    quality: 95
                });
                
                log(`✅ 摄像头切换成功! 当前: ${currentCameraIndex === 0 ? '后置' : '前置'}`, 'success');
                updateCameraStatus();
                
            } catch (error) {
                log(`❌ 摄像头切换失败: ${error.message}`, 'error');
                console.error('Switch camera error:', error);
                // 尝试恢复
                currentCameraIndex = currentCameraIndex === 0 ? 1 : 0;
            } finally {
                hideLoading();
            }
        }
        
        async function releaseCamera() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (cameraInstance) {
                    log('释放相机资源...', 'info');
                    
                    try {
                        await cameraInstance.releaseSession();
                        log('✅ 相机会话已释放', 'info');
                    } catch (e) {
                        log(`⚠️ 释放会话时出现警告: ${e.message}`, 'warning');
                        console.error('Release session error:', e);
                    }
                    
                    try {
                        await cameraInstance.releaseCamera();
                        log('✅ 相机资源释放成功', 'success');
                    } catch (e) {
                        log(`⚠️ 释放相机时出现警告: ${e.message}`, 'warning');
                        console.error('Release camera error:', e);
                    }
                    
                    cameraInstance = null;
                    currentCameraIndex = 0;
                    updateCameraStatus();
                } else {
                    log('没有需要释放的相机资源', 'warning');
                }
                
            } catch (error) {
                log(`❌ 释放相机失败: ${error.message}`, 'error');
                console.error('Release camera error:', error);
            } finally {
                hideLoading();
            }
        }
        
        // 高级相机功能
        async function testZoom() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                log('开始变焦测试...', 'info');
                
                const zoomLevels = [1.0, 2.0, 3.0, 1.5, 1.0];
                
                for (let i = 0; i < zoomLevels.length; i++) {
                    const zoomRatio = zoomLevels[i];
                    try {
                        const result = await cameraInstance.setZoomRatio(zoomRatio);
                        if (result) {
                            log(`✅ 变焦设置成功: ${zoomRatio}x`, 'success');
                        } else {
                            log(`❌ 变焦设置失败: ${zoomRatio}x`, 'error');
                        }
                        
                        if (i < zoomLevels.length - 1) {
                            await new Promise(resolve => setTimeout(resolve, 1000));
                        }
                    } catch (zoomError) {
                        log(`❌ 变焦 ${zoomRatio}x 设置异常: ${zoomError.message}`, 'error');
                        console.error('Zoom error:', zoomError);
                    }
                }
                
                log('✅ 变焦测试完成', 'success');
                
            } catch (error) {
                log(`❌ 变焦测试失败: ${error.message}`, 'error');
                console.error('Zoom test error:', error);
            } finally {
                hideLoading();
            }
        }
        
        async function testFlash() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                log('开始闪光灯测试...', 'info');
                
                const flashModes = [
                    { mode: 0, name: '关闭' },
                    { mode: 1, name: '开启' },
                    { mode: 2, name: '自动' },
                    { mode: 0, name: '关闭' }
                ];
                
                for (let i = 0; i < flashModes.length; i++) {
                    const { mode, name } = flashModes[i];
                    try {
                        await cameraInstance.setFlashMode(mode);
                        log(`✅ 闪光灯模式设置成功: ${name} (${mode})`, 'success');
                        
                        if (i < flashModes.length - 1) {
                            await new Promise(resolve => setTimeout(resolve, 1000));
                        }
                    } catch (flashError) {
                        log(`❌ 闪光灯模式 ${name} 设置失败: ${flashError.message}`, 'error');
                    }
                }
                
                log('✅ 闪光灯测试完成', 'success');
                
            } catch (error) {
                log(`❌ 闪光灯测试失败: ${error.message}`, 'error');
                console.error('Flash test error:', error);
            } finally {
                hideLoading();
            }
        }
        
        async function testFocus() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                log('开始对焦测试...', 'info');
                
                const focusPoints = [
                    { x: 0.3, y: 0.3, name: '左上' },
                    { x: 0.7, y: 0.3, name: '右上' },
                    { x: 0.5, y: 0.5, name: '中心' },
                    { x: 0.3, y: 0.7, name: '左下' },
                    { x: 0.7, y: 0.7, name: '右下' }
                ];
                
                for (let i = 0; i < focusPoints.length; i++) {
                    const { x, y, name } = focusPoints[i];
                    try {
                        const result = await cameraInstance.setFocusPoint(x, y);
                        if (result) {
                            log(`✅ 对焦点 ${name} 设置成功: (${x}, ${y})`, 'success');
                        } else {
                            log(`❌ 对焦点 ${name} 设置失败: (${x}, ${y})`, 'error');
                        }
                        
                        if (i < focusPoints.length - 1) {
                            await new Promise(resolve => setTimeout(resolve, 1000));
                        }
                    } catch (focusError) {
                        log(`❌ 对焦点 ${name} 设置异常: ${focusError.message}`, 'error');
                    }
                }
                
                log('✅ 对焦测试完成', 'success');
                
            } catch (error) {
                log(`❌ 对焦测试失败: ${error.message}`, 'error');
                console.error('Focus test error:', error);
            } finally {
                hideLoading();
            }
        }
        
        async function getVideoFrameInfo() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                log('获取视频帧信息...', 'info');
                
                const frameInfo = await cameraInstance.getVideoFrameInfo();
                log(`视频帧信息: ${frameInfo.width}x${frameInfo.height} @ ${frameInfo.frameRate}fps`, 'success');
                
            } catch (error) {
                log(`获取视频帧信息失败: ${error.message}`, 'error');
            } finally {
                hideLoading();
            }
        }
        
        // 视频录制
        async function startVideoRecording() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                if (isRecording) {
                    throw new Error('已在录制中，请先停止当前录制');
                }
                
                log('开始视频录制...', 'info');
                
                const videoSurfaceId = `video_surface_${Date.now()}`;
                const photoSurfaceId = `photo_surface_${Date.now()}`;
                
                const result = await cameraInstance.startVideoRecording(videoSurfaceId, photoSurfaceId);
                
                if (result) {
                    isRecording = true;
                    button.textContent = '录制中...';
                    button.classList.add('danger');
                    
                    log(`✅ 视频录制开始成功 - Video Surface: ${videoSurfaceId}`, 'success');
                    
                    // 检查视频防抖
                    try {
                        const stabilization = await cameraInstance.checkVideoStabilization(1);
                        if (stabilization) {
                            log('🎥 视频防抖检查: 支持', 'info');
                        } else {
                            log('🎥 视频防抖检查: 不支持', 'info');
                        }
                    } catch (stabError) {
                        log(`⚠️ 视频防抖检查失败: ${stabError.message}`, 'warning');
                    }
                } else {
                    log('❌ 开始录制失败', 'error');
                }
                
            } catch (error) {
                log(`❌ 开始视频录制失败: ${error.message}`, 'error');
                console.error('Start recording error:', error);
            } finally {
                hideLoading();
            }
        }
        
        async function stopVideoRecording() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化');
                }
                
                if (!isRecording) {
                    throw new Error('当前没有在录制');
                }
                
                log('停止视频录制...', 'info');
                
                const result = await cameraInstance.stopVideoRecording();
                
                if (result) {
                    isRecording = false;
                    const startButton = document.querySelector('button[onclick="startVideoRecording()"]');
                    if (startButton) {
                        startButton.textContent = '开始录制';
                        startButton.classList.remove('danger');
                    }
                    
                    log('✅ 视频录制停止成功', 'success');
                    
                    // 获取视频帧信息
                    try {
                        const frameInfo = await cameraInstance.getVideoFrameInfo();
                        if (frameInfo) {
                            log(`📹 视频帧信息: ${JSON.stringify(frameInfo)}`, 'info');
                        }
                    } catch (frameError) {
                        log(`⚠️ 获取视频帧信息失败: ${frameError.message}`, 'warning');
                    }
                } else {
                    log('❌ 停止录制失败', 'error');
                }
                
            } catch (error) {
                log(`❌ 停止视频录制失败: ${error.message}`, 'error');
                console.error('Stop recording error:', error);
            } finally {
                hideLoading();
            }
        }
        
        async function testVideoStabilization() {
            const button = event.target;
            const hideLoading = showLoading(button);
            
            try {
                if (!cameraInstance || !cameraInstance.isReady()) {
                    throw new Error('相机未初始化，请先点击"初始化相机"');
                }
                
                log('测试视频防抖功能...', 'info');
                
                await cameraInstance.checkVideoStabilization(1);
                log('视频防抖模式1支持', 'success');
                
            } catch (error) {
                log(`视频防抖测试: ${error.message}`, 'warning');
            } finally {
                hideLoading();
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            log('📱 页面加载完成，开始初始化...', 'info');
            
            // 初始化相机状态显示
            updateCameraStatus();
            
            // 检查 window 对象上的可用属性
            log('🔍 检查 window 对象...', 'info');
            log('window.HarmonyBridge: ' + (typeof window.HarmonyBridge), 'info');
            log('window.CameraBridge: ' + (typeof window.CameraBridge), 'info');
            
            // 等待 CameraBridge 注册完成
            let checkCount = 0;
            const maxChecks = 10;
            const checkInterval = setInterval(() => {
                checkCount++;
                log(`🔄 检查 CameraBridge (${checkCount}/${maxChecks})...`, 'info');
                
                if (typeof window.CameraBridge !== 'undefined') {
                    log('✅ CameraBridge 可用', 'success');
                    try {
                        log('CameraBridge 构造函数: ' + window.CameraBridge.toString().substring(0, 100) + '...', 'info');
                    } catch (e) {
                        log('CameraBridge 构造函数信息获取失败', 'warning');
                    }
                    clearInterval(checkInterval);
                    
                } else if (checkCount >= maxChecks) {
                    log('❌ CameraBridge 不可用，请确保在 HarmonyOS 环境中运行', 'error');
                    const bridgeKeys = Object.keys(window).filter(key => 
                        key.includes('Bridge') || key.includes('Camera') || key.includes('Harmony')
                    );
                    log('可用的相关属性: ' + (bridgeKeys.length > 0 ? bridgeKeys.join(', ') : '无'), 'info');
                    clearInterval(checkInterval);
                }
            }, 200); // 每 200ms 检查一次，总共检查 2 秒
        });
    </script>
</body>
</html>